#ifndef BAIDU_TTS_CLIENT_H
#define BAIDU_TTS_CLIENT_H

#include <QObject>
#include <QNetworkAccessManager>
#include <QNetworkRequest>
#include <QNetworkReply>
#include <QTimer>
#include <QJsonDocument>
#include <QJsonObject>
#include <QBuffer>
#include <QAudioOutput>
#include <QAudioFormat>
#include <QTemporaryFile>
#include <QProcess>

class BaiduTTSClient : public QObject
{
    Q_OBJECT

public:
    explicit BaiduTTSClient(QObject *parent = nullptr);
    ~BaiduTTSClient();

    // 初始化和配置
    bool initialize(const QString &appId, const QString &apiKey, const QString &secretKey);
    bool isInitialized() const { return m_initialized; }

    // 语音合成
    bool synthesizeText(const QString &text);
    void stopSynthesis();
    bool isSynthesizing() const { return m_synthesizing; }

    // 设置参数
    void setVoice(const QString &voice) { m_voice = voice; }
    void setSpeed(int speed) { m_speed = qBound(0, speed, 15); }
    void setPitch(int pitch) { m_pitch = qBound(0, pitch, 15); }
    void setVolume(int volume) { m_volume = qBound(0, volume, 15); }
    void setLanguage(const QString &language) { m_language = language; }

    QString getLastError() const { return m_lastError; }

signals:
    void synthesisStarted();
    void synthesisFinished();
    void synthesisError(const QString &error);
    void audioDataReady(const QByteArray &audioData);

private slots:
    void onTokenReplyFinished();
    void onTTSReplyFinished();
    void onAudioOutputStateChanged(QAudio::State state);

private:
    // 网络相关
    QNetworkAccessManager *m_networkManager;
    QNetworkReply *m_currentReply;

    // 音频相关
    QAudioOutput *m_audioOutput;
    QBuffer *m_audioBuffer;
    QTemporaryFile *m_tempAudioFile;

    // 百度API配置
    QString m_appId;
    QString m_apiKey;
    QString m_secretKey;
    QString m_accessToken;
    qint64 m_tokenExpireTime;

    // TTS参数
    QString m_voice;        // 发音人 (per)
    int m_speed;           // 语速 (spd) 0-15
    int m_pitch;           // 音调 (pit) 0-15  
    int m_volume;          // 音量 (vol) 0-15
    QString m_language;    // 语言 (lan)

    // 状态
    bool m_initialized;
    bool m_synthesizing;
    QString m_lastError;

    // URL常量
    static const QString TOKEN_URL;
    static const QString TTS_URL;

    // 内部方法
    void requestAccessToken();
    bool isTokenValid() const;
    void setLastError(const QString &error);
    QString urlEncode(const QString &text);
    void setupAudioOutput();
    void playAudioData(const QByteArray &audioData);
};

#endif // BAIDU_TTS_CLIENT_H 